Euler Problem 1 : Code Optimization / Alternatives [on hold]
Posted
by
Sudhakar
on Programmers
See other posts from Programmers
or by Sudhakar
Published on 2013-07-03T14:31:56Z
Indexed on
2013/07/03
17:18 UTC
Read the original article
Hit count: 329
optimization
|algorithm-analysis
I am new bee into the world of Datastructures and algorithms from ground up. This is my attempt to learn.
If the question is very plain/simple . Please bear with me.
Problem:
Find the sum of all the multiples of 3 or 5 below 1000.
Code i worte:
package problem1;
public class Problem1 {
public static void main(String[] args) {
//******************Approach 1****************
long start = System.currentTimeMillis();
int total = 0;
int toSubtract = 0;
//Complexity N/3
int limit = 10000;
for(int i=3 ; i<limit ;i=i+3){
total = total +i;
}
//Complexity N/5
for(int i=5 ; i<limit ;i=i+5){
total = total +i;
}
//Complexity N/15
for(int i=15 ; i<limit ;i=i+15){
toSubtract = toSubtract +i;
}
//9N/15 = 0.6 N
System.out.println(total-toSubtract);
System.out.println("Completed in "+(System.currentTimeMillis() - start));
//******************Approach 2****************
for(int i=3 ; i<limit ;i=i+3){
total = total +i;
}
for(int i=5 ; i<limit ;i=i+5){
if ( 0 != (i%3)) total = total +i;
}
}
}
Question 1 - Which best approach from the above code and why ? 2 - Are there any better alternatives ?
© Programmers or respective owner